package com.mtcarpenter.base64;

import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

/**
 * @Author: mtcarpenter
 * @describe
 * @Date: 2019/10/8
 * @Version 1.0
 */
public class Base64Test {

    /**
     * Base64 编码 解码
     */
    @Test
    public void test01() {
        try {
            // 编码
            String base64encoded = Base64.getEncoder().encodeToString(
                    "Java 8 新特性必知必会 ".getBytes("utf-8"));
            System.out.println("编码: " + base64encoded);
            // 解码
            byte[] base64decoded = Base64.getDecoder().decode(base64encoded);
            System.out.println("解码：" + new String(base64decoded, "utf-8"));

        } catch (UnsupportedEncodingException e) {
            System.out.println("编码解码异常：" + e.getMessage());
        }
    }


    /**
     * MIME  Base64 编码解码器
     */
    @Test
    public void test02() {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 5; ++i) {
                stringBuilder.append(UUID.randomUUID().toString());
            }
            // 编码
            byte[] bytes = stringBuilder.toString().getBytes("utf-8");
            String mimeEncoded = Base64.getMimeEncoder().encodeToString(bytes);
            System.out.println("加密：" + mimeEncoded);
            // 解码
            byte[] base64decoded = Base64.getMimeDecoder().decode(mimeEncoded);
            System.out.println("解码：" + new String(base64decoded, "utf-8"));

        } catch (UnsupportedEncodingException e) {
            System.out.println("编码解码异常：" + e.getMessage());
        }
    }

    /**
     * url 和 文件名安全的编码解码器
     */
    @Test
    public void test03() {
        try {
            // 编码
            String base64encoded = Base64.getUrlEncoder().encodeToString(
                    "Java 8 新特性必知必会 ".getBytes("utf-8"));
            System.out.println("编码：" + base64encoded);

            // 解码
            byte[] base64decodedBytes = Base64.getUrlDecoder().decode(base64encoded);
            System.out.println("解码：" + new String(base64decodedBytes, "utf-8"));

        } catch (UnsupportedEncodingException e) {
            System.out.println("编码解码异常：" + e.getMessage());
        }
    }
}
